package com.jiajia.study.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiajia.common.utils.PageUtils;
import com.jiajia.common.utils.Query;
import com.jiajia.study.product.dao.AttrDao;
import com.jiajia.study.product.entity.AttrAttrgroupRelationEntity;
import com.jiajia.study.product.entity.AttrEntity;
import com.jiajia.study.product.entity.AttrGroupEntity;
import com.jiajia.study.product.entity.CategoryEntity;
import com.jiajia.study.product.enums.AttrTypeEnum;
import com.jiajia.study.product.service.AttrAttrgroupRelationService;
import com.jiajia.study.product.service.AttrGroupService;
import com.jiajia.study.product.service.AttrService;
import com.jiajia.study.product.service.CategoryService;
import com.jiajia.study.product.vo.AttrRestVO;
import com.jiajia.study.product.vo.AttrVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttr(AttrVO attrVO) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtil.copyProperties(attrVO,attrEntity);
        this.save(attrEntity);

        if(AttrTypeEnum.BASE_ATTR.getType().equals(attrEntity.getAttrType())){
            // 分类和属性关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params,Long catelogId,Integer attrType) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();


        if(null != attrType){
            queryWrapper.eq("attr_type",attrType);
        }
        if(null != catelogId && 0 != catelogId){
            queryWrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            queryWrapper.and(
                    a-> a.eq("catelog_id",key)
                    .or().like("attr_name",key)
            );
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrRestVO> resultList= records.stream().map(item->{
            AttrRestVO attrRestVO = new AttrRestVO();
            BeanUtil.copyProperties(item,attrRestVO);

            AttrAttrgroupRelationEntity attrAttrGroupRelation = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));

            if(null !=  attrAttrGroupRelation){
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrGroupRelation.getAttrGroupId());
                if(null != attrGroupEntity){
                    attrRestVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryService.getById(item.getCatelogId());
            if(null != categoryEntity){
                attrRestVO.setCatelogName(categoryEntity.getName());
            }
            return attrRestVO;
        }).collect(Collectors.toList());

        pageUtils.setList(resultList);
        return pageUtils;
    }

    @Override
    public AttrRestVO getInfoById(Long attrId) {
        AttrRestVO attrRestVO = new AttrRestVO();

        // 基本属性
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtil.copyProperties(attrEntity,attrRestVO);


        // 分类路径
        CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
        if(null != categoryEntity){
            Long[] catelogPath = categoryService.findCatelogPath(categoryEntity.getCatId());
            attrRestVO.setCatelogPath(catelogPath);
        }


        List<AttrAttrgroupRelationEntity> relationEntities =  attrAttrgroupRelationService.getByAttrId(attrEntity.getAttrId());
        if(null == relationEntities || list().isEmpty()){
            return attrRestVO;
        }


        if(AttrTypeEnum.BASE_ATTR.getType().equals(attrEntity.getAttrType())){
            // 属性 -> 属性分组 是一对一
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationEntities.get(0);
            attrRestVO.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());

            AttrGroupEntity attrGroup = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
            if(null != attrGroup){
                attrRestVO.setGroupName(attrGroup.getAttrGroupName());
            }
        }



        return attrRestVO;
    }

    @Override
    @Transactional
    public void updateInfoById(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtil.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        // 修改属性和属性分组的关联关系
        if(AttrTypeEnum.BASE_ATTR.getType().equals(attrEntity.getAttrType())){
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.getByAttrId(attrEntity.getAttrId());
            if(null == relationEntities || relationEntities.isEmpty()){
                // 新增关联关系
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
            }else {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationEntities.get(0);
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.updateById(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {

        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationService.getByAttrGroupId(attrGroupId);
        List<Long> attrIds = relations.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        if(attrIds.isEmpty()){
            return new ArrayList<>();
        }
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("attr_id",attrIds);
        return this.list(queryWrapper);
    }

}
